<template>
  <div v-loading="allLoading" class="police-basic-infor">
    <Custom-tree @leafNodeClick="getNodeData"></Custom-tree>
    <div class="right">
      <CustomSearch v-if="form.jsh" ref="searchRef" v-model:form="form" :showRest="false" @search="getData">
        <template #moreHandle>
          <el-button type="primary" @click="asyncData" plain>
            <el-icon size="16"><Refresh /></el-icon>
            重新同步</el-button
          >
        </template>
        <template #right>
          <div class="update-time">
            <span class="status" :style="{ color: status == 'querying' ? '#409eff' : status == 'finish' ? '#67C23A' : 'red' }">
              <el-icon v-if="status == 'finish'" color="#67C23A"><CircleCheck /></el-icon> {{ statusTitle }}</span
            >
            <span class="time" v-if="updateInfor.time">最后更新时间 {{ updateInfor.time }} (IP:{{ updateInfor.ip }})</span>
          </div>
        </template>
      </CustomSearch>
      <!-- <div v-else class="no-data"></div> -->
      <template v-if="form.jsh">
        <el-card body-class="list-card" v-loading="loading" style="margin-top: 10rem">
          <el-scrollbar height="874rem">
            <div class="table-wrap" v-for="(item, index) in tableData" :key="item.rybh">
              <table border>
                <colgroup>
                  <col width="5%" class="flash" />
                  <col width="12%" class="flash" />
                  <col width="12%" class="flash" />
                  <col width="12%" class="flash" />
                  <col width="15%" class="flash" />
                  <col width="20%" class="flash" />
                  <col width="24%" class="flash" />
                </colgroup>
                <tr>
                  <th class="index" width="80px">序号</th>
                  <th class="origin">数据来源</th>
                  <th class="name">姓名</th>
                  <th class="photo">照片</th>
                  <th class="card-number">卡号</th>
                  <th class="idcard">身份证号</th>
                  <th>密码</th>
                </tr>
                <tr>
                  <th rowspan="2" class="order">{{ index + 1 }}</th>
                  <td class="origin">数据库</td>
                  <td class="name">{{ item.mjmz }}</td>
                  <td class="photo">
                    <el-popover v-if="item.zpurl" placement="right" :width="600" trigger="hover" content="">
                      <img :src="item.zpurl + '?token=' + userStore.token" style="width: 100%" />
                      <template #reference>
                        <img v-if="item.zpurl" class="avatar" :src="item.zpurl + '?token=' + userStore.token" />
                      </template>
                    </el-popover>
                  </td>
                  <td class="card-number">{{ item.kh }}</td>
                  <td class="idcard">{{ item.sfzh }}</td>
                  <td>{{ item.password }}</td>
                </tr>
                <tr>
                  <td class="origin">终端</td>
                  <td class="name">{{ searchByRybh(item).mjmz }}</td>
                  <td class="photo">
                    <el-popover v-if="searchByRybh(item).zpurl" placement="right" :width="600" trigger="hover" content="">
                      <img :src="searchByRybh(item).zpurl" style="width: 100%" />
                      <template #reference>
                        <img v-if="searchByRybh(item).zpurl" class="avatar" :src="searchByRybh(item).zpurl" />
                      </template>
                    </el-popover>
                  </td>
                  <td class="card-number">{{ searchByRybh(item).kh }}</td>
                  <td class="idcard">{{ searchByRybh(item).sfzh }}</td>
                  <td>{{ searchByRybh(item).password }}</td>
                </tr>
              </table>
            </div>
          </el-scrollbar>
        </el-card>
      </template>
      <el-card v-else class="no-room-data">
        <custom-empty height="924rem"></custom-empty>
      </el-card>
    </div>
  </div>
</template>

<script setup name="policeCheck">
import { ref, onBeforeMount, onMounted, computed, watch, onBeforeUnmount, reactive } from 'vue'

import { http, getArrFirstData } from '@/utils/index.js'
import { stores } from '@/stores/index.js'
import Stomp from 'stompjs'
import { ElMessage } from 'element-plus'

let stompClient = null
let timer = null //websoket  断开重连定时器
let wsData = {} //websoket地址信息
const userStore = stores.useUserStore()
const props = defineProps({})
const allLoading = ref(false)
const loading = ref(false)
const status = ref('noSignal') //终端推送数据状态
const currentUnit = ref({})
const updateInfor = ref({})
const tableData = ref([]) //数据库查询到数据
const personData = ref([]) // websoket 推送的数据

const form = ref({
  jsh: ''
})

const statusTitle = computed(() => {
  return status.value == 'noSignal' ? '未查询到监室终端数据' : status.value == 'finish' ? '监室终端数据查询成功' : '正在查询监室终端数据..'
})

onMounted(async () => {
  getWsUrl()
})
onBeforeUnmount(() => {
  clearTimeout(timer)
  if (stompClient !== null) {
    stompClient.disconnect()
  }
})
const getNodeData = async (node) => {
  currentUnit.value = node
  await getJsh()
  getData()
}
//获取websockt 地址
const getWsUrl = () => {
  allLoading.value = true
  http('/znjszd3/ht/cnpDataVerify/getWsForCnpDataVerify', 'get', {
    type: 'mjxx'
  })
    .then((res) => {
      wsData = res.data
      connectStomp()
    })
    .finally(() => {
      allLoading.value = false
    })
}
const connectStomp = () => {
  clearTimeout(timer)
  if (stompClient !== null) {
    stompClient.disconnect()
  }
  const ws = new WebSocket(wsData.wsUrl)
  stompClient = Stomp.over(ws)
  // stompClient.heartbeat.outgoing = 60000
  // stompClient.heartbeat.incoming = 60000
  stompClient.debug = () => {}
  stompClient.connect(
    { username: '' },
    () => {
      stompClient.subscribe(wsData.wsDestination, function (message) {
        const msg = JSON.parse(message.body)

        if (msg.doWhat !== 'getMjxxListFromCnping') {
          status.value = 'querying'
        }
        if (msg.doWhat == 'getMjxxListFromCnpFinish') {
          personData.value = msg.data || []
          status.value = 'finish'
        }
      })
    },
    () => {
      console.log('stomp断开了')
      timer = setTimeout(() => {
        connectStomp()
      }, 2000)
    }
  )
}
function getJsh() {
  form.value.jsh = ''
  return http('/znjszd3/comm/getJshsByDwdm', 'get', {
    type: 'tree',
    dwdm: currentUnit.value.zddm
  }).then(async (res) => {
    console.log(res)

    const jsh = getArrFirstData(res.data).zddm || ''
    form.value.jsh = jsh

    // initWebsockt()
  })
}
//获取民警信息
function getData(params = {}) {
  if (!form.value.jsh) return ElMessage.warning('当前监所无监室')
  personData.value = []
  loading.value = true
  status.value = 'noSignal'
  http('/znjszd3/ht/cnpDataVerify/getMjxxByDwdm', 'get', {
    dwdm: currentUnit.value.zddm,
    jsh: form.value.jsh
  })
    .then((res) => {
      tableData.value = res.data.list
      updateInfor.value = res.data.cnpDownLog
    })
    .finally(() => {
      loading.value = false
    })
}

//通过人员编号查询对应的终端数据
const searchByRybh = (person) => {
  const obj = personData.value.find((item) => item.id == person.id)
  if (obj) {
    return obj
  } else {
    return {}
  }
}

const asyncData = () => {
  ElMessageBox.confirm(`是否立即通知 ${form.value.jsh}监室终端重新同步数据?`, '', {
    confirmButtonText: '是',
    cancelButtonText: '否',
    type: 'infor'
  })
    .then(() => {
      loading.value = true
      http('/znjszd3/ht/cnpDataVerify/telCnpUpdateRyxxMjxx', 'get', {
        jsh: form.value.jsh,
        dwdm: currentUnit.value.zddm
      })
        .then((res) => {
          console.log(res)
          if (res.status == 200) {
            ElMessage.success(res.message.join())
          }
        })
        .finally(() => {
          loading.value = false
        })
    })
    .catch(() => {})
}
</script>
<style lang="scss" scoped>
.police-basic-infor {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  ::v-deep(.custom-search) {
    .search-btn {
      grid-area: 1 / 2 / span 1 / span 3;
    }
  }
  // height: 965rem;
  .right {
    padding: 10px;
    width: calc(100% - 200px);
    .update-time {
      position: absolute;
      right: 50px;
      top: 30px;
      color: #6a7678;
      font-size: 16px;
      .time {
        position: relative;
        margin-left: 30px;
        &::before {
          position: absolute;
          top: 2px;
          left: -15px;
          display: block;
          content: '';
          width: 3px;
          height: 14px;
          background: #ccc;
        }
      }
    }
  }
}
.no-data {
  min-height: 56px;
  background-color: #fff;
  border-radius: 4px;
}
.no-room-data {
  background: #fff;
}
.table-wrap {
  border-radius: 4px;
  overflow: hidden;
  border: 2px solid transparent;
  margin-bottom: 15px;
  &:hover {
    border-color: var(--el-color-primary-light-5);
  }
}
.tip {
  margin-bottom: 5px;
  font-size: 16px;
  display: flex;
  justify-content: space-between;
  color: var(--el-color-primary);
}

::v-deep(.list-card) {
  padding: 10px !important;
}
::v-deep(.search.el-card) {
  margin-bottom: 8px;

  .el-form-item {
    margin-bottom: 0;
  }
}
table {
  width: 100%;
  border-collapse: collapse;

  th.index {
    // width: 5%;
  }
  th.order {
    font-size: 22px;
    font-weight: 700;
    color: #1b3945;
  }
  th,
  td {
    text-align: center;
    vertical-align: middle;
    // width: calc(71% / 10);
    border: 1px solid #ebebeb;
  }

  th:not(.order) {
    height: 50px;
    background-color: var(--el-color-primary-light-9);
  }

  td {
    height: 60px;
    img {
      display: inline-block;
      height: 90%;
      border: none;
    }
  }
  td.photo {
    padding-top: 3px;
  }
  .terminal td {
    background-color: #f2f3f5;
  }

  .finger,
  .avatar {
    margin-top: 3px;
    // cursor: pointer;
  }
}
</style>
